package com.lry.jvm.rtda.heap;

import com.lry.jvm.rtda.JObject;

import java.util.HashMap;
import java.util.Map;

public class StringPool {
    private static final Map<String, JObject> internedStrings = new HashMap();

    public static JObject JString(JClassLoader loader,String str){
        JObject internedStr = internedStrings.get(str);
        if(null!=internedStr){
            return internedStr;
        }
        //new String ,value里放char数组cs
        char[] cs = str.toCharArray();
        JObject jChars = new JObject(loader.loadClass("[C"),cs);
        JObject jStr = new JObject(loader.loadClass("java/lang/String"));
        jStr.setRefVar("value","[C",jChars);
        internedStrings.put(str,jStr);
        return jStr;
    }

    public static String javaString(JObject arrRef){
        JObject jChars = arrRef.getRefVar("value","[C");
        char[] cs = (char[]) jChars.getData();
        return new String(cs);
    }
}
